export const useHistory = () => {
  const subscribe = (callback: () => void) => {
    // 监听浏览器历史记录的变化，特别是当用户点击浏览器的前进/后退按钮时触发
    window.addEventListener('popstate', callback);
    // 当 URL 的片段标识符（以 # 符号开头和之后的 URL 部分）更改时，将触发 hashchange 事件
    window.addEventListener('hashchange', callback);
    return () => {
      window.removeEventListener('popstate', callback);
      window.removeEventListener('hashchange', callback);
    };
  };
  const getSnapshot = () => {
    return window.location.href;
  };

  const push = (path: string) => {
    // pushState(state, unused, url)
    window.history.pushState(null,'',path);
    window.dispatchEvent(new PopStateEvent('popstate'));
  };

  const replace = (path:string) => {
    window.history.replaceState(null,'',path);
    window.dispatchEvent(new PopStateEvent('popstate'));
  }

  const res = useSyncExternalStore(subscribe, getSnapshot);

  return [res,push,replace] as const;
};
